/*
 * producer_consumer.h
 *
 *  Created on: May 8, 2009
 *      Author: lapoija
 */

#ifndef PRODUCER_CONSUMER_H_
#define PRODUCER_CONSUMER_H_

#include <pthread.h>
#include "thread_extensions.h"
#include <semaphore.h>
#include <errno.h>
#include <time.h>
#include <stdbool.h>

//static pthread_mutex_t requests_lock = PTHREAD_MUTEX_INITIALIZER;

/*
 * Structure request_t
 *
 * The request structure for the producer consumer thread.
 */
typedef struct request
{
   unsigned int isValid :1; // 1 bit (0 or 1)
   unsigned int isNullTerm :1; // 1 bit (0 or 1)
   unsigned int req_length :8; // 0 <= req_length <= 255
   char * req; // 32 bit memory address pointing to a max length char
// structure of 255 bytes
} request_t;

/*
 * Simple request_list structure which contains a linked-list of request_t
 * structures
 */
typedef struct request_list
{
   struct request_list * prev;
   request_t * data;
   struct request_list * next;
} request_list_t;

/*
 * Container for the linked list and associated meta-data
 */
typedef struct request_list_container
{
   bool isInitialized;
   request_list_t * dataHead; // points to head of linked list data.
   request_list_t * dataTail; // points to tail of linked list data.
   int (*add)(request_t *req_t); // pointer to add function
   int (*remove)(request_t*); // pointer to remove function
   unsigned int max_length; // maximum length of linked list data buffer
   unsigned int count; // current count of linked list data.
   pthread_mutex_t mutex; // shared mutex exposed for exclusive access to struct.
   pthread_cond_t producerCond; // producer conditional synch object.
   pthread_cond_t consumerCond; // consumer conditional synch object.
} request_list_container_t;

/******************************************************************************
 * Constant declarations
 *****************************************************************************/
#define OPERATION_SUCCESS (0)
#define LIST_FULL (-1)
#define LIST_EMPTY (-1)
#define LIST_NULL (-2)
#define OUT_DATA_NULL (-3)
#define DEFAULT_LIST_SIZE (8)

/******************************************************************************
 * Function definitions
 *****************************************************************************/

/*
 * This function initializes the mutex and thread attribute variables and MUST
 * be called before any other function in this file.
 */
void initMutex();

request_list_container_t * initContainer(unsigned int max_length);
request_list_container_t * initContainerForce(unsigned int maxLength, bool isForce);

void initRequest(request_t * out_data);

#endif /* PRODUCER_CONSUMER_H_ */
